//
//  YYPlayDetailViewController.swift
//  STMusic
//
//  Created by stoneobs on 17/4/17.
//  Copyright © 2017年 stoneobs. All rights reserved.
//
//**********************播放详情页面***************************
import UIKit
import AVFoundation
class YYPlayDetailViewController: STTableViewController {

    var musicID:String! //播放ID
    
    var backgroundImageUrl:String? = "";
    
    var type:String = "";//2 视屏 1 音频
    
    
    var musicResouce:String?{
        didSet{
            self.playView?.videoUrl = self.musicResouce;
        }
    }//资源地址
    
    var musicDetailModel:YYMusicDeatailModel?
    
    var cureentVoiceUrl:String?
    
    
    var playView:STVideoPlayView? //播放view
    
    var bottomView:UIView?//底部view
    
    var textFiledView:UITextField?
    
    
    
    //乐评播放
    var avplayer:AVPlayer?
    
    var avPlayerItem:AVPlayerItem?

    
    deinit {
        print("释放了");
    }
    init(musicID:String) {
        super.init(style: .grouped);
        self.musicID = musicID;
        
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //MARK:VC 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configSubview();
        
        self.automaticallyAdjustsScrollViewInsets = false;
        self.view.backgroundColor = YYThemeStyleManger.defultManger.gradualColor(frame: self.view.bounds);
        self.tableView.frame = CGRect.init(x: 0, y: (self.playView?.bottom)!, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - (self.playView?.height)!  - 50 - 20);
        self.tableView.backgroundColor = YYThemeStyleManger.defultManger.gradualColor(frame: self.tableView.bounds);
        self.tableView.allowsSelection = true;
        self.tableView.register(YYMusciCommentCell.self, forCellReuseIdentifier: "YYMusciCommentCell");
        self.tableView.register(YYCommentCell.self, forCellReuseIdentifier: "YYCommentCell");
        self.tableView.register(YYReplyCommentCell.self, forCellReuseIdentifier: "YYReplyCommentCell");
        
        //获取详情和资源文件请求
        self.sendTheVideoResouceRequest(musicID: self.musicID, type: "0",successHandle: {});
        self.sendTheMusicDetailRequest();
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);
        self.hideNavagetionbar();
        YYDefaultMusicAnimationView.sharedInstance.isHidden = true;

    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        YYDefaultMusicAnimationView.sharedInstance.isHidden = true;
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated);
        self.showNavagationbar();
        self.navigationController?.navigationBar.barTintColor = YYThemeStyleManger.defultManger.gradualColor(frame:(self.navigationController?.navigationBar.bounds)!);

    }

        // MARK:Config Subview
    func configSubview() -> Void {
        
        self.playView = STVideoPlayView.init(frame: CGRect.init(x: 0, y: 20, width: SCREEN_WIDTH, height: SCREEN_HEIGHT / 2), andVideoUrl: "");
        self.playView?.backGroundImageUrl = self.backgroundImageUrl;
        self.playView?.shouldHideImageViewWhenReady = false;
        if type == "2" {
            self.playView?.shouldHideImageViewWhenReady = true;
        }
        weak var weakSelf = self;
        self.playView?.backActionHandle = {
            weakSelf?.playView?.pause();
            _ = weakSelf?.navigationController?.popViewController(animated: true)
        
        }
        self.view.addSubview(self.playView!);
        
        self.bottomView = UIView.init(frame: .init(x: 0, y: 0, width: SCREEN_WIDTH, height: 50));
        self.bottomView?.backgroundColor = UIColor.init(gradientStyle: .leftToRight, withFrame: (self.bottomView?.bounds)!, andColors: [FlatBlack(),FlatBlackDark()]);
        self.bottomView?.bottom = SCREEN_HEIGHT;
        self.view.addSubview(self.bottomView!);
        
        self.textFiledView = UITextField.init(frame: .init(x: 15, y: 0, width: SCREEN_WIDTH - 30, height: 38));
        self.textFiledView?.placeholder = "  期待你的神评论";
        self.textFiledView?.centerY = 25;
        self.textFiledView?.backgroundColor = .white;
        self.textFiledView?.layer.cornerRadius = (self.textFiledView?.height)! / 2;
        self.textFiledView?.clipsToBounds = true;
        self.textFiledView?.textColor = .white;
        self.bottomView?.addSubview(self.textFiledView!);
        
    }

      // MARK: UITableView DataSouce
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 2;
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 && (self.musicDetailModel != nil){
            return (self.musicDetailModel?.recommend?.recommentList.count)!;
        }else if section == 1 && (self.musicDetailModel != nil){
            return (self.musicDetailModel?.comment?.commentList.count)!;
        }
        return 0 ;
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return CGFloat(YYMusciCommentCell.YYMusciCommentCellHeight);
        }
        if indexPath.section == 1 {
            if self.musicDetailModel?.comment?.commentList[indexPath.row].origin_comment?.words != ""{
            
                let cell: YYReplyCommentCell = YYReplyCommentCell.init(style: .default, reuseIdentifier: "height");
                cell.model = self.musicDetailModel?.comment?.commentList[indexPath.row];
                return cell.YYCommentCellHeight!;
                
            }
            return CGFloat(YYCommentCell.YYCommentCellHeight);
        }
        return 30;
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1{
            return 10;
        }
        return 0.01;
    }
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01;
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            weak  var  weakSelf = self;
        if indexPath.section == 0 {
            let cell:YYMusciCommentCell = tableView.dequeueReusableCell(withIdentifier: "YYMusciCommentCell") as! YYMusciCommentCell;
            cell.model = self.musicDetailModel?.recommend?.recommentList[indexPath.row];
            //点击头像
            cell.headView?.iconButton?.clicAction = {[weak cell] button in
                let userModel = cell?.model?.user;
                weakSelf?.iconAction(model: userModel!);
            }
            //点击语音
            cell.commentView?.imageViewActionHandle = {[weak cell]  imageView in
                weakSelf?.voiceAction(cell: cell!);
            }
            //点击查看详情
            cell.scanDetailButton?.clicAction = {[weak cell]  button in
            
                weakSelf?.detailMusicCommentAction(model: (cell?.model!)!)
            }
            return cell;
        }
        if indexPath.section == 1{
        
            if self.musicDetailModel?.comment?.commentList[indexPath.row].origin_comment?.words != ""{
                //回复的cell
                let cell:YYReplyCommentCell = tableView.dequeueReusableCell(withIdentifier: "YYReplyCommentCell") as! YYReplyCommentCell;
                cell.model = self.musicDetailModel?.comment?.commentList[indexPath.row];
                cell.originCommentButton?.clicAction = {[weak cell] but  in
                //点击回复
                    weakSelf?.cellOriginButtonAction(model: (cell?.model)!);
                }
                //点击头像
                cell.headView?.iconButton?.clicAction = {[weak cell] but in
                    weakSelf?.iconAction(model: (cell?.model?.user)!);
                }
                return cell;
                
            }
            else{
                 //评论的cell
                let cell:YYCommentCell = tableView.dequeueReusableCell(withIdentifier: "YYCommentCell") as! YYCommentCell;
                cell.model = self.musicDetailModel?.comment?.commentList[indexPath.row];
                //点击头像
                cell.headView?.iconButton?.clicAction = {[weak cell] but in
                    weakSelf?.iconAction(model: (cell?.model?.user)!);
                }
                return cell;
            }

        }

        return UITableViewCell();
    }
    
    // MARK: UITableView Delegate
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false);
        let cell = tableView.cellForRow(at: indexPath);
        if !(cell?.isKind(of: YYMusciCommentCell.self))!{
        
            let model:YYCommentModel = (self.musicDetailModel?.comment?.commentList[indexPath.row])!;
            
            self.cellAction(model: model);
        }
        
    }


    // MARK:Network Request
    //获取资源请求
    func sendTheVideoResouceRequest(musicID:String, type:String ,successHandle:@escaping () -> Void) -> Void {
        YYSuiYueNetWorkManger.defultManger.postNetwork(urlString: "https://api.suiyueyule.com/1.0.2/resource/downloadUrl?lang=utf8", dic: ["id":musicID,"type":type], successHandle: { (json) in
            if type == "0" {
                let dic = json["data"] as! NSDictionary;
                self.musicResouce = dic["url"] as? String;
            }else if type == "2" {
                let dic = json["data"] as! NSDictionary;
                self.cureentVoiceUrl = dic["url"] as? String;
            }
            successHandle();

        }) { (des) in
            print("error des = \(des)");
        }
    }

    //获取详情
    func sendTheMusicDetailRequest() -> Void {
        //https://api.suiyueyule.com/1.0.2/works/details/63492?lang=utf8&r=feed/follow
        let url = "https://api.suiyueyule.com/1.0.2/works/details/\(self.musicID!)?lang=utf8&r=feed/follow";
        YYSuiYueNetWorkManger.defultManger.getNetwork(urlString: url, dic: [:], successHandle: { (json) in
            
            let mydic = json["data"] as? NSDictionary;
            
            self.musicDetailModel = YYMusicDeatailModel.mj_object(withKeyValues: mydic);
            weak var weakSelf = self;
            self.playView?.title = self.musicDetailModel?.works?.title;
            self.type = (self.musicDetailModel?.works?.type)!;
            if self.type == "2" {
                self.playView?.shouldHideImageViewWhenReady = true;
            }
            let header = YYMusicDetailHeader.init(frame: .init(x: 0, y: 0, width: SCREEN_WIDTH, height: 600));
            header.model = self.musicDetailModel;
            header.downloadButton?.clicAction = { but in
            
                weakSelf?.downloadAction();
            }
            header.iconButton?.clicAction = {[weak header] but in
                weakSelf?.iconAction(model: (header?.model?.user)!);
            }
            header.attentionButton?.clicAction = {but in
            
                weakSelf?.attentionAction(but: but!);
            }
            header.scoreView?.imageHandle = { tag in
                weakSelf?.scoreXingXingAction(diffcultNum: tag);
            };

            self.tableView.tableHeaderView = header;
            self.tableView.reloadData();
            
            if (self.musicDetailModel?.comment?.commentList.count)! >= 4 {
                self.tableView.mj_footer = MJChiBaoZiFooter.init(refreshingBlock: {

                    //新增评论
                    weakSelf?.send_Get_MoreComments_Request(lastcommentID: (weakSelf?.musicDetailModel?.comment?.commentList.last?.id?.description)!)
                });
            }
            
        }) { (des) in
            
        }
    }

    func send_Get_MoreComments_Request(lastcommentID:String) -> Void {
        let url = "https://api.suiyueyule.com/1.0.2/works/comment/general/\(self.musicID!)?lang=utf8&comment_id=\(lastcommentID)&limit=20";
        
        YYSuiYueNetWorkManger.defultManger.getNetwork(urlString: url, dic: [:], successHandle: { (json) in
            
            self.tableView.mj_footer.endRefreshing();
            let dic:[String:Any] = json["data"] as! Dictionary;
            if   let array:Array<[String:Any]> = dic["general_comment_arr"] as? Array {
            
                if array.count == 0{
                    self.tableView.mj_footer.endRefreshingWithNoMoreData();
                }
                for dic in array {
                    let model = YYCommentModel.mj_object(withKeyValues: dic);
                    self.musicDetailModel?.comment?.commentList.append(model!);
                
                }
                self.tableView.reloadData();
               
            
            };
            
            
            
        }) { (failDes) in
            
            self.tableView.mj_footer.endRefreshing();
        }
    }
    
        //MARK:Action
    //header action
    //点击了下载
    func downloadAction() {
        print("点击了下载")
    }
    func attentionAction(but:UIButton) {
        print("点击了关注")
    }
    //点击了分数
    func scoreXingXingAction(diffcultNum:Int) {
        print("点击了分数\(diffcultNum)")
    }
    //点击了语音
    func voiceAction(cell:YYMusciCommentCell) {
        print("点击了语音")
        
        self.playView?.pause();
        //正在播放，停止
        if cell.commentView?.imageView?.isAnimating == true{
            self.avplayer?.pause();
            cell.commentView?.imageView?.stopAnimating();
        }else{
            
            self.sendTheVideoResouceRequest(musicID: (cell.model?.file?.id)!, type: "2", successHandle: {
                cell.commentView?.imageView?.startAnimating();
                self.avPlayerItem = AVPlayerItem.init(url: URL.init(string: (self.cureentVoiceUrl!))!);
                self.avplayer = AVPlayer.init(playerItem: self.avPlayerItem);
                self.avplayer?.play();
            })
            
        }
    }
    //点击了查看详情
    func detailMusicCommentAction(model:YYRecommendModel) {
        print("点击了查看详情")
    }

    //点击了头像
    func iconAction(model:YYuserModel)  {
        print("点击了头像 user is \(model)")
    }
    //点击了某个cell
    func cellAction(model:YYCommentModel)  {
         print("点击了cell,model is \(model)")
    }
    //点击了某个初始评论
    func cellOriginButtonAction(model:YYCommentModel)  {
        print("点击了初始评论,origin comment is \(model)")
    }

}
